<template>
  <el-card class="box-card">
    <div class="text item">
      <h2>配置输入源</h2>
    </div>
    <el-form ref="configForm">
      <!-- 按钮用于显示 USB 设备选择弹窗 -->
      <el-form-item class="centered-buttons">
        <el-button @click="showUsbDialog = true">选择 USB 摄像头</el-button>
        <el-button @click="showNetworkStreamDialog = true">网络视频流</el-button>
        <el-button @click="showViewDialog = true">选择视角</el-button>
        <el-button @click="showVideoPath = true">视频路径</el-button><br><br>
        <span style="font-size: 16px; margin-right: 20px">当前输入源:</span>
        <span>{{ selectedDevice }}</span><br>
        <span style="font-size: 16px; margin-right: 20px">当前视角:</span>
        <span>{{ selectView }}</span>
        <!--        <div v-model=""></div>-->
      </el-form-item>

      <!-- USB 设备选择弹窗 -->
      <el-dialog title="选择 USB 设备" :visible.sync="showUsbDialog">
        <el-select v-model="temporarySelectedUsbDevice" placeholder="请选择 USB 设备">
          <el-option v-for="device in usbDevices" :key="device.id" :label="device.name" :value="device.number" />
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showUsbDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmUsbDevice">确定</el-button>
        </div>
      </el-dialog>

      <!-- 网络视频流配置弹窗 -->
      <el-dialog title="配置网络视频流" :visible.sync="showNetworkStreamDialog">
        <el-input v-model="networkConfig.ip" placeholder="IP 地址" />
        <el-input v-model="networkConfig.port" placeholder="端口" style="margin-top: 10px;" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="showNetworkStreamDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmNetworkStream">确定</el-button>
        </div>
      </el-dialog>

      <!-- 视频路径配置弹窗 -->
      <el-dialog title="视频路径" :visible.sync="showVideoPath">
        <el-input v-model="inputVideoPath" placeholder="请输入本地路径" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="showVideoPath = false">取消</el-button>
          <el-button type="primary" @click="confirmVideoPath">确定</el-button>
        </div>
      </el-dialog>

      <!-- 视角选择弹窗 -->
      <el-dialog title="选择视角" :visible.sync="showViewDialog">
        <el-select v-model="temporarySelectedView" placeholder="请选择视角">
          <el-option v-for="view in visualView" :key="view.id" :label="view.name" :value="view.value" />
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showViewDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmVisualView">确定</el-button>
        </div>
      </el-dialog>

      <!-- <div class="text item">
        <h2>视频存储路径设置</h2>
      </div>

      <el-form-item>
        <label>当前视频存储路径：</label>
        <span>{{ videoStoragePath }}</span>
        <el-button class="path-change-button" size="small" @click="showVideoPathDialog = true">修改路径</el-button>
      </el-form-item>

      <div class="text item">
        <h2>图片存储路径设置</h2>
      </div>
      <el-form-item>
        <label>当前图片存储路径：</label>
        <span>{{ imageStoragePath }}</span>
        <el-button class="path-change-button" size="small" @click="showImagePathDialog = true">修改路径</el-button>
      </el-form-item> -->

      <div class="text item">
        <h2>检测阈值设置</h2>
      </div>
      <!-- 检测阈值等相关参数设置 -->
      <el-form-item>
        <label>当前阈值设置:</label>
        <span>{{ threshold }}</span>
        <el-button class="path-change-button" size="small" @click="showThresholdDialog = true">修改阈值</el-button>
      </el-form-item>

      <!--
      <el-form-item>
        <el-button @click="showVideoPathDialog = true">选择路径</el-button>
        <div v-if="finalSelectedPath" class="selected-path">
          选定路径：{{ finalSelectedPath }}
        </div>
      </el-form-item>

      <el-form-item>
        <el-button @click="showImagePathDialog = true">选择路径</el-button>
        <div v-if="finalSelectedPath" class="selected-path">
          选定路径：{{ finalSelectedPath }}
        </div>
      </el-form-item>

      <el-form-item>
        <el-button @click="submitConfig">提交配置</el-button>
      </el-form-item>
    </el-form> -->

      <!-- 视频目录选择器弹窗 -->
      <!-- 新的路径输入弹窗 -->
      <!-- <el-dialog title="修改存储路径" :visible.sync="showVideoPathDialog">
        <el-input v-model="newPath" placeholder="请输入新的路径" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="showVideoPathDialog = false">取消</el-button>
          <el-button type="primary" @click="submitNewPath">确认</el-button>
        </div>
      </el-dialog> -->

      <!-- 图片目录选择器弹窗 -->
      <!-- 新的路径输入弹窗 -->
      <!-- <el-dialog title="修改存储路径" :visible.sync="showImagePathDialog">
        <el-input v-model="newPath" placeholder="请输入新的路径" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="showImagePathDialog = false">取消</el-button>
          <el-button type="primary" @click="submitImageNewPath">确认</el-button>
        </div>
      </el-dialog> -->

      <!-- 阈值输入弹窗 -->
      <!-- 新的阈值输入 -->
      <el-dialog title="修改阈值" :visible.sync="showThresholdDialog">
        <el-input v-model="newThreshold" placeholder="请输入新的阈值" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="showThresholdDialog = false">取消</el-button>
          <el-button type="primary" @click="submitThreshold">确认</el-button>
        </div>
      </el-dialog>
    </el-form>
  </el-card>
</template>

<script>
import { Message } from 'element-ui'
import { getThreshold, setThreshold, setView } from '@/api/systemconfig'

export default {
  data() {
    return {
      inputSource: 'usb', // 'usb' 或 'network'

      // 输入路径
      newPath: '', // 用户输入的新路径

      // 新的阈值
      newThreshold: '',

      // usb
      showUsbDialog: false, // 控制 USB 设备选择弹窗的显示
      usbDevices: [
        { id: 1, number: '1', name: 'USB 设备 1' },
        { id: 2, number: '2', name: 'USB 设备 2' },
        { id: 3, number: '3', name: 'USB 设备 3' }
        // 添加更多的假数据来模拟在线的 USB 设备
      ],
      //   selectedUsbDevice: null, // 用户选择的 USB 设备
      temporarySelectedUsbDevice: '',
      selectedUsbDevice: '',
      selectedDevice: '请选择当前输入源',
      isUSB: '',
      isLocalPath: '',

      // network
      showNetworkStreamDialog: false,
      networkStreamConfigured: false,
      networkConfig: {
        ip: '',
        port: ''
      },

      // view
      showViewDialog: false,
      showVideoPath: false,
      selectView: '',
      visualView: [
        {
          id: 1, name: '单视角', value: 1
        },
        {
          id: 2, name: '双视角', value: 2
        }
      ],
      temporarySelectedView: '',

      // video save path
      videoStoragePath: 'C:/videos', // 假设的初始视频存储路径
      showVideoPathDialog: false, // 控制录片存储路径弹窗

      // picture save path
      imageStoragePath: 'C:/image', // 录片存储路径
      showImagePathDialog: false, // 控制录片存储路径弹窗

      // threshold value
      threshold: '',
      showThresholdDialog: false,

      // 输入路径配置
      inputVideoPath: '',

      // a
      temporarySelectedPath: '', // 临时存储用户选择的路径
      finalSelectedPath: '', // 最终确定的路径
      videoPath: '', // 最终确定的路径
      storageConfig: {
        videoPath: '',
        imagePath: ''
      },
      dialogVisible: false, // 控制弹窗的显示
      availablePaths: ['路径1', '路径2', '路径3'], // 可用的存储路径
      // 其他数据
      directories: [
        { id: 1, name: 'Folder 1', children: [{ id: 2, name: 'Subfolder 1-1' }, { id: 3, name: 'Subfolder 1-2' }] },
        { id: 4, name: 'Folder 2', children: [{ id: 5, name: 'Subfolder 2-1' }] },
        { id: 6, name: 'Folder 3' }
      ],

      // 展开目录
      currentExpandedNode: null // 当前被展开的节点信息
    }
  },
  computed: {
    foundObject() {
      return this.visualView.find(item => item.value === this.temporarySelectedView)
    },
    foundName() {
      return this.foundObject ? this.foundObject.name : null
    }
  },
  created() {
    this.getvideopath()
    this.getimagepath()
    this.getThreshold()
    // this.fetchFolderData()
    // this.enhanceTreeData(this.directories)
  },
  methods: {
    // 新增方法确定输入路径
    confirmVideoPath() {
      //  更新页面显示
      this.isLocalPath = true
      this.isUSB = false
      this.videoPath = this.inputVideoPath
      this.currentDevice()
      this.showVideoPath = false // 关闭弹窗
      Message({
        message: `修改输入视频路径成功`,
        type: 'success',
        duration: 4000 // 持续时间 3000 毫秒
      })
      console.log('确定的路径:', this.finalSelectedPath)
    },
    // 新增方法判断当前UsbDevice
    currentDevice() {
      if (this.isUSB) {
        console.log(this.selectedUsbDevice)
        this.selectedDevice = 'USB设备' + this.selectedUsbDevice
      } else if (this.isLocalPath) {
        this.selectedDevice = this.inputVideoPath
      }
    },
    getvideopath() {
      const param = {
        path: this.newPath
      }
      this.$store.dispatch('systemconfig/getvideopath', param)
        .then(response => {
          // 假设后端返回的数据格式为 { directories: [...] }
          this.videoStoragePath = response.data.path
        })
        .catch(error => {
          console.error('获取根目录失败:', error)
        })
    },
    getimagepath() {
      const param = {
        path: this.newPath
      }
      this.$store.dispatch('systemconfig/getimagepath', param)
        .then(response => {
          // 假设后端返回的数据格式为 { directories: [...] }
          this.imageStoragePath = response.data.path
        })
        .catch(error => {
          console.error('获取根目录失败:', error)
        })
    },
    getThreshold() {
      getThreshold()
        .then(response => {
          this.threshold = response.threshold
        })
        .catch(error => {
          console.error('获取阈值失败:', error)
        })
    },
    submitVideoNewPath() {
      const param = {
        path: this.newPath
      }
      this.$store.dispatch('systemconfig/setvideopath', param).then(response => {
        if (response.success) {
          this.showPathInputDialog = false
          Message({
            message: '路径更新成功',
            type: 'success',
            duration: 3000
          })
          this.videoStoragePath = this.newPath
        }
      })
    },
    submitNewPath() {
      const param = {
        path: this.newPath
      }
      this.$store.dispatch('systemconfig/setvideopath', param)
        .then(response => {
          // 假设后端返回的数据格式为 { directories: [...] }
          this.videoStoragePath = this.newPath
          this.showVideoPathDialog = false
          Message({
            message: '路径更新成功',
            type: 'success',
            duration: 3000
          })
        })
        .catch(error => {
          console.error('获取根目录失败:', error)
        })
    },
    submitImageNewPath() {
      const param = {
        path: this.newPath
      }
      this.$store.dispatch('systemconfig/setimagepath', param)
        .then(response => {
          this.imageStoragePath = this.newPath
          this.showImagePathDialog = false // 关闭弹窗
          Message({
            message: '路径更新成功',
            type: 'success',
            duration: 3000
          })
        })
        .catch(error => {
          console.error('获取根目录失败:', error)
        })
    },
    submitThreshold() {
      const parm = this.newThreshold
      setThreshold(parm)
        .then(response => {
          this.threshold = this.newThreshold
          this.showThresholdDialog = false
          Message({
            message: '阈值设置成功',
            type: 'success',
            duration: 3000
          })
        })
        .catch(error => {
          console.error('阈值设置失败:', error)
        })
    },
    submitConfig() {
      // 提交配置到后端的逻辑
      // ...
    },
    handleNodeClick(data) {
      this.temporarySelectedPath = data.name // 更新临时选择的路径
    },
    // 获取文件夹数据的方法（需要后端支持）
    fetchFolderData() {
      // 发送请求到后端，获取根目录结构数据
      // const param = {
      //   type: this.inputSource
      // }
      this.$store.dispatch('systemconfig/getfiletree')
        .then(response => {
          // 假设后端返回的数据格式为 { directories: [...] }
          this.directories = response.data
        })
        .catch(error => {
          console.error('获取根目录失败:', error)
        })
      // 发送请求到后端，获取文件夹结构数据
    },
    confirmVideoSelection() {
      // 假设 temporarySelectedPath 是用户在弹窗中选择的新路径
      this.videoStoragePath = this.temporarySelectedPath
      this.finalSelectedPath = this.temporarySelectedPath // 确认选择
      this.showVideoPathDialog = false // 关闭弹窗
      Message({
        message: `修改视频路径成功`,
        type: 'success',
        duration: 4000 // 持续时间 3000 毫秒
      })
      console.log('确定的路径:', this.finalSelectedPath)
    },
    confirmNetworkStream() {
      this.inputSource = '2'
      this.showNetworkStreamDialog = false
      this.networkStreamConfigured = true
      // 这里可以添加进一步处理网络视频流配置的代码
      // 显示设置成功的消息，并在三秒后消失
      const param = {
        type: this.inputSource,
        ip: this.networkConfig.ip,
        port: this.networkConfig.port
      }
      this.$store.dispatch('systemconfig/inputconfig', param)
        .then((response) => {
          // 请求成功，处理后端返回的数据
          const responseData = response.data
          // this.videoList = responseData
          console.log('设置NetworkStream设备', responseData)
          Message({
            message: `网络视频流配置成功：IP 地址 - ${this.networkConfig.ip}, 端口 - ${this.networkConfig.port}`,
            type: 'success',
            duration: 4000 // 持续时间 3000 毫秒
          })
        })
        .catch((error) => {
          // 请求失败，处理错误
          console.error('Error:', error)
          Message({
            message: `设置失败`,
            type: 'error',
            duration: 4000
          })
        })
    },
    confirmUsbDevice() {
      this.inputSource = '1'
      this.selectedUsbDevice = this.temporarySelectedUsbDevice
      this.showUsbDialog = false
      const param = {
        type: this.inputSource,
        usbnumber: this.selectedUsbDevice
      }
      console.log('this.selectedUsbDevice:', this.selectedUsbDevice)
      // 发送到searchvideo处理
      this.$store.dispatch('systemconfig/inputconfig', param)
        .then((response) => {
          // 成功则在页面显示
          this.isUSB = true
          this.currentDevice()
          // 请求成功，处理后端返回的数据
          const responseData = response.data
          // this.videoList = responseData
          console.log('设置usb设备', responseData)
          Message({
            message: `USB ${this.temporarySelectedUsbDevice} 设备设置成功`,
            type: 'success',
            duration: 4000
          })
        })
        .catch((error) => {
          // 请求失败，处理错误
          console.error('Error:', error)
          Message({
            message: `设置失败`,
            type: 'error',
            duration: 4000
          })
        })
    },
    confirmVisualView() {
      const parm = this.temporarySelectedView
      setView(parm)
        .then(response => {
          this.selectView = this.foundName
          this.showViewDialog = false
          Message({
            message: '视角设置成功',
            type: 'success',
            duration: 3000
          })
        })
        .catch(error => {
          console.error('视角设置失败:', error)
        })
    },
    // 方法来确认录片存储路径的选择
    confirmImagePathSelection() {
      // ...实现...
      // 假设 temporarySelectedPath 是用户在弹窗中选择的新路径
      this.imageStoragePath = this.temporarySelectedPath
      this.finalSelectedPath = this.temporarySelectedPath // 确认选择
      //   this.showVideoPathDialog = false // 关闭弹窗
      this.showImagePathDialog = false
      Message({
        message: `修改图片路径成功`,
        type: 'success',
        duration: 4000 // 持续时间 4000 毫秒
      })
      console.log('确定的路径:', this.finalSelectedPath)
    },
    enhanceTreeData(data, parent = null) {
      data.forEach(node => {
        node.parent = parent
        if (node.children && node.children.length > 0) {
          this.enhanceTreeData(node.children, node)
        }
      })
    },
    handleNodeExpand(node, reslove) {
      // 设置当前展开的节点
      this.currentExpandedNode = node
      //
      const path = [node.label]
      let current = node.parent
      while (current) {
        path.unshift(current.label) // 将父节点的 label 添加到路径数组的开头
        current = current.parent
      }
      const fullPath = '/' + path.join('/')
      console.log('完整路径:', fullPath)
      // 发送请求到后端，获取当前节点下的文件
      // 假设后端接口为 'getDirectoryContents'，并且需要节点的 id 作为参数
      const param = {
        path: node.name
      }
      this.$store.dispatch('systemconfig/getfiletree', param)
        .then(response => {
          // 假设后端返回的数据格式为 { children: [...] }
          // 更新当前节点的子节点
          this.$set(node, 'children', response.data.children)
        })
        .catch(error => {
          console.error('获取目录内容失败:', error)
        })
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.text.item h2 {
  text-align: center;
}

.el-form-item {
  margin-bottom: 60px;
}

.selected-path {
  margin-top: 10px;
}

.path-change-button {
  margin-left: 80px;
  /* 或者根据需要调整 */
}

.centered-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
